//
//  HRSayHelloViewController.m
//  Hear
//
//  Created by mac on 2017/8/23.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRSayHelloViewController.h"
#import "HREnterTextFiledView.h"
#import "EMVoiceConverter.h"
#import "HRDynamicCell.h"

@interface HRSayHelloViewController ()
@property (nonatomic, strong)HREnterTextFiledView *textFiledView;

@property (strong, nonatomic) HRMessageToolBar *chatToolbar;
@property(strong, nonatomic) EaseFaceView *faceView;
@property(strong, nonatomic) HRMeeageRecordView *recordView;

@property (weak, nonatomic) id<EaseMessageViewControllerDataSource> dataSource;
@property (weak, nonatomic) id<EaseMessageViewControllerDelegate> delegate;

@property (nonatomic, strong)HRSoundButton *soundButton;

@end

@implementation HRSayHelloViewController
#pragma mark - Get and Set
- (HRSoundButton *)soundButton {
    if (_soundButton == nil) {
        _soundButton = [HRSoundButton buttonWithType:0];
        _soundButton.frame = CGRectMake(self.textFiledView.left, self.textFiledView.top+5, 170, 50);
        _soundButton.voiceImageView.frame = CGRectMake(15, 5, 30, 20);
        [_soundButton setImage:[UIImage imageNamed:@"语音播放长条"] forState:0];
        _soundButton.voiceTimeLabel.frame = CGRectMake(_soundButton.voiceImageView.right, 0, _soundButton.width-_soundButton.voiceImageView.right-15, _soundButton.height);

    }
    return _soundButton;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    [self setupView];
}

- (void)setupView{
    self.title = @"打招呼";
    
//    UIButton *leftButton = [UIButton buttonWithType:0];
//    leftButton.size = CGSizeMake(20, 20);
//    [leftButton setImage:[UIImage imageNamed:@"Back-Arrow"] forState:UIControlStateNormal];
//    [leftButton addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
//    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    
    UILabel *descLabel = [UILabel new];
    descLabel.text = @"说句打招呼的话";
    descLabel.font = CustomUIFont(15);
    descLabel.textColor =FirstTextColor;
    [self.view  addSubview:descLabel];
    descLabel.frame = CGRectMake(20, 80, 150, 20);
    
    
    
    UILabel *topLabel = [UILabel new];
    topLabel.backgroundColor = CustomColor(240, 240, 240, 1);
    [self.view  addSubview:topLabel];
    topLabel.frame = CGRectMake(0, descLabel.bottom+15, kFullWidth, 1);
    self.textFiledView = [[HREnterTextFiledView alloc] initWithFrame:CGRectMake(20, topLabel.bottom, kFullWidth-40, 40)];
    self.textFiledView.line.hidden = YES;
    self.textFiledView.textField.textColor = SecondTextColor;
    [self.view addSubview:self.textFiledView];
    UILabel *bottomLabel = [UILabel new];
    bottomLabel.backgroundColor = CustomColor(240, 240, 240, 1);
    [self.view  addSubview:bottomLabel];
    bottomLabel.frame = CGRectMake(0, self.textFiledView.bottom, kFullWidth, 1);
    
    
    self.chatToolbar = [[HRMessageToolBar alloc] initWithFrame:CGRectMake(0, kFullHeight- 50, kFullWidth, 50) keyboardType:DXKeyboardTypeVoiceAndNoTextViewInput];
    self.chatToolbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    
    
    [self setupEmotion];
    
}

- (void)clickBack{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:NO];

}


/*!
 @method
 @brief 设置表情
 @discussion 加载默认表情，如果子类实现了dataSource的自定义表情回调，同时会加载自定义表情
 @result
 */
- (void)setupEmotion
{
    if ([self.dataSource respondsToSelector:@selector(emotionFormessageViewController:)]) {
        NSArray* emotionManagers = [self.dataSource emotionFormessageViewController:self];
        [self.faceView setEmotionManagers:emotionManagers];
    } else {
        NSMutableArray *emotions = [NSMutableArray array];
        for (NSString *name in [EaseEmoji allEmoji]) {
            EaseEmotion *emotion = [[EaseEmotion alloc] initWithName:@"" emotionId:name emotionThumbnail:name emotionOriginal:name emotionOriginalURL:@"" emotionType:EMEmotionDefault];
            [emotions addObject:emotion];
        }
        EaseEmotion *emotion = [emotions objectAtIndex:0];
        EaseEmotionManager *manager= [[EaseEmotionManager alloc] initWithType:EMEmotionDefault emotionRow:3 emotionCol:7 emotions:emotions tagImage:[UIImage imageNamed:emotion.emotionId]];
        [self.faceView setEmotionManagers:@[manager]];
    }
}


- (void)setChatToolbar:(HRMessageToolBar *)chatToolbar
{
    [_chatToolbar removeFromSuperview];
    
    _chatToolbar = chatToolbar;
    if (_chatToolbar) {
        [self.view addSubview:_chatToolbar];
    }
    
    if ([chatToolbar isKindOfClass:[HRMessageToolBar class]]) {
        [(HRMessageToolBar *)self.chatToolbar setDelegate:self];
        //        self.chatBarMoreView = (EaseChatBarMoreView*)[(HRMessageToolBar *)self.chatToolbar moreView];
        self.faceView = (EaseFaceView*)[(HRMessageToolBar *)self.chatToolbar faceView];
        self.faceView.delegate = self;
    }
}


#pragma mark EMFaceDelegate
- (void)selectedFacialView:(NSString *)str isDelete:(BOOL)isDelete{
    NSString *chatText = self.textFiledView.textField.text;
    
    if (!isDelete && str.length > 0) {
        self.textFiledView.textField.text = [NSString stringWithFormat:@"%@%@",chatText,str];
    }
}


-(void)didSelectButton:(BOOL)isSelect{
    if (isSelect){
        [self.textFiledView.textField resignFirstResponder];
    }else{
        [self.textFiledView.textField becomeFirstResponder];
    }
}


- (void)setDataSource:(id<EaseMessageViewControllerDataSource>)dataSource
{
    //    _dataSource = dataSource;
    
    [self setupEmotion];
}


- (void)didStartRecordingVoiceAction:(UIView *)recordView
{
    
    
    
    
    if ([self _canRecord]) {
        
        int x = arc4random() % 100000;
        NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
        NSString *fileName = [NSString stringWithFormat:@"%d%d",(int)time,x];
        
        [[EMCDDeviceManager sharedInstance] asyncStartRecordingWithFileName:fileName completion:^(NSError *error)
         {
             if (error) {
                 NSLog(@"%@",NSEaseLocalizedString(@"message.startRecordFail", @"failure to start recording"));
             }
         }];
    }
}

- (void)didCancelRecordingVoiceAction:(UIView *)recordView
{
    [[EMCDDeviceManager sharedInstance] cancelCurrentRecording];
    
}

#pragma 发送语音
- (void)didFinishRecoingVoiceAction:(UIView *)recordView andRecordPath:(NSString *)recordPath andDuration:(NSInteger)aDuration
{
    
    NSString *wavFilePath = [[recordPath stringByDeletingPathExtension]
                             stringByAppendingPathExtension:@"wav"];
    BOOL convertResult = [self convertAMR:recordPath toWAV:wavFilePath];
    if (convertResult){
        NSFileManager *fm = [NSFileManager defaultManager];
        [fm removeItemAtPath:recordPath error:nil];
        
    }else{
        
    }
    
    self.textFiledView.hidden = YES;
    self.soundButton.soundUrl = recordPath;
    [self.view addSubview:self.soundButton];
    
//    [self answerComment:wavFilePath andType:@"2" andUrlLength:[NSString stringWithFormat:@"%d",aDuration]];
}

- (BOOL)convertAMR:(NSString *)amrFilePath
             toWAV:(NSString *)wavFilePath
{
    BOOL ret = NO;
    BOOL isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:amrFilePath];
    if (isFileExists) {
        [EMVoiceConverter amrToWav:amrFilePath wavSavePath:wavFilePath];
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:wavFilePath];
        if (isFileExists) {
            ret = YES;
        }
    }
    
    return ret;
}

- (void)didDragInsideAction:(UIView *)recordView
{
    if ([self.recordView isKindOfClass:[HRMeeageRecordView class]]) {
        [(HRMeeageRecordView *)self.recordView recordButtonDragInside];
    }
}

- (void)didDragOutsideAction:(UIView *)recordView
{
    if ([self.recordView isKindOfClass:[HRMeeageRecordView class]]) {
        [(HRMeeageRecordView *)self.recordView recordButtonDragOutside];
    }
}

- (BOOL)_canRecord
{
    __block BOOL bCanRecord = YES;
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
    {
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
            [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                bCanRecord = granted;
            }];
        }
    }
    
    return bCanRecord;
}



-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.hidesBottomBarWhenPushed = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
